package com.asia5b.a5mall.home.activity

import android.text.TextUtils
import cn.bingoogolapple.qrcode.core.BarcodeType
import cn.bingoogolapple.qrcode.core.QRCodeView
import com.alibaba.android.arouter.facade.annotation.Route
import com.asia5b.a5bmall.resource.ActCons
import com.asia5b.a5mall.home.R
import com.asia5b.a5mall.home.databinding.ActivityScanBinding
import com.asia5b.a5mall.middleware.base.SimpleActivity
import com.asia5b.a5mall.middleware.base.SimpleViewModel
import com.asia5b.a5mall.middleware.utils.*
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.listener.OnResultCallbackListener
import kotlinx.android.synthetic.main.activity_scan.*
import timber.log.Timber
import java.lang.Exception

/**
 * 扫一扫
 */
@Route(path = ActCons.ScanActivity)
class ScanActivity : SimpleActivity<SimpleViewModel, ActivityScanBinding>(), QRCodeView.Delegate {


    override val viewModelClazz: Class<SimpleViewModel>
        get() = SimpleViewModel::class.java

    override fun getDataBinding(): ActivityScanBinding {
        return ActivityScanBinding.inflate(layoutInflater)
    }

    private val mZBarView by lazy {
        zbarview
    }

    private var lightOpen = false

    override fun initView() {
        mZBarView.setDelegate(this)
    }

    override fun initEvent() {
        ll_scan_light.setOnClickListener {
//            CodeUtils.isLightEnable(!lightOpen)
            lightOpen = !lightOpen
            if (lightOpen) {
                mZBarView.openFlashlight()
            } else {
                mZBarView.closeFlashlight()
            }
            if (lightOpen) {
                tv_scan_light.setText(R.string.关灯)
                iv_scan_light.setImageResource(R.drawable.ic_light_open)
            } else {
                iv_scan_light.setImageResource(R.drawable.ic_light_close)
                tv_scan_light.setText(R.string.开灯)
            }
        }
        ll_scan_photo.setOnClickListener {
            openPicture(callback = object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(selectList: MutableList<LocalMedia>?) {
                    if (!selectList.isNullOrEmpty()) {
                        val localMedia = selectList[0]
                        val path = localMedia.compressPath
                        if (!TextUtils.isEmpty(path)) {
                            mZBarView.decodeQRCode(path)
                        }


                    }
                }

                override fun onCancel() {
                }

            })
        }
    }

    override fun initData() {

    }

    private fun vibrate() {
        //        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        //        vibrator.vibrate(200);
    }

    var isStartActivity = false
    override fun onScanQRCodeSuccess(result: String?) {
        Timber.d(String.format("--->>>>>>>>---result:$result"));
        vibrate()
        if (mZBarView != null) {
            mZBarView.startSpot() // 开始识别
        }
        val showToast = {
            showMessage(getString(R.string.识别无效))
        }
        if (!TextUtils.isEmpty(result)) {
            if (result!!.contains("goods/") && result!!.contains("su=")) {
                if (!isStartActivity) {
                    isStartActivity = true
                    startGoodsDetailActivity(mActivity, RegularHelper().getMiddleString(result, "goods/", "\\?su=")[0].toInt())
                }
            } else if (result!!.contains("shop/")) {
                val split = result!!.split("shop/")
                if (split.size > 1) {
                    try {
                        val shopId = split[1].toInt()
                        if (!isStartActivity) {
                            isStartActivity = true
                            startShopActivity(mActivity, shopId)
                        }
                    } catch (e: Exception) {

                    }
                }
            } else {
                showToast.invoke()
            }
        } else {
            showToast.invoke()
        }

    }

    override fun onCameraAmbientBrightnessChanged(isDark: Boolean) {
        // 这里是通过修改提示文案来展示环境是否过暗的状态，接入方也可以根据 isDark 的值来实现其他交互效果
        //        String tipText = mZBarView.getScanBoxView().getTipText();
        //        String ambientBrightnessTip = "\n环境过暗，请打开闪光灯";
        //        if (isDark) {
        //            if (!tipText.contains(ambientBrightnessTip)) {
        //                mZBarView.getScanBoxView().setTipText(tipText + ambientBrightnessTip);
        //            }
        //        } else {
        //            if (tipText.contains(ambientBrightnessTip)) {
        //                tipText = tipText.substring(0, tipText.indexOf(ambientBrightnessTip));
        //                mZBarView.getScanBoxView().setTipText(tipText);
        //            }
        //        }
    }

    override fun onScanQRCodeOpenCameraError() {
        showMessage(getString(R.string.识别失败))
    }

    override fun onResume() {
        super.onResume()
        isStartActivity = false
    }

    override fun onStart() {
        super.onStart()
        if (mZBarView != null) {
            mZBarView.startCamera() // 打开后置摄像头开始预览，但是并未开始识别
            mZBarView.changeToScanQRCodeStyle() // 切换成扫描二维码样式
            mZBarView.setType(BarcodeType.TWO_DIMENSION, null) // 只识别二维条码
            mZBarView.startSpotAndShowRect() // 显示扫描框，并开始识别
        }
    }

    override fun onStop() {
        if (mZBarView != null) {
            mZBarView.stopCamera() // 关闭摄像头预览，并且隐藏扫描框
        }
        super.onStop()
    }

    override fun onDestroy() {
        if (mZBarView != null) {
            mZBarView.onDestroy() // 销毁二维码扫描控件
        }
        super.onDestroy()
    }

}